package com.lifeng.zk.zkclient;

import com.lifeng.zk.vo.User;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

/**
 * Created by lifeng on 2018/6/14.
 */
public class ZkClientTest {
    private static String serverUrl = "127.0.0.1:2181";

    public static void main(String[] args) throws Exception{
        ZkClient zkClient = new ZkClient(serverUrl);
        System.out.println("zkclient 链接成功");
        /*String node = zkClient.create("/test","真是的", CreateMode.PERSISTENT);
        System.out.println("节点创建成功:"+node);*/

        //创建递归目录(递归创建不能设置数据)
        //zkClient.createPersistent("/test/aaa/dd/fg/gg",true);
        /*User user = new User();
        user.setId("1111");
        user.setName("这是");
        user.setDate(new Date());
        String node = zkClient.create("/li",user,CreateMode.PERSISTENT);
        System.out.println("创建node:"+node);*/

        //获取数据
        /*String data = zkClient.readData("/test");
        System.out.println("读取数据:"+data);
        String data1 = zkClient.readData("/test/qwe",true);//true时节点不存在时返回null，false时不存在抛异常
        System.out.println("读取数据:"+data1);
        User user1 = zkClient.readData("/li",true);
        System.out.println(user1);*/

        //设置数据
        //zkClient.writeData("/li","1111111111111");
        //zkClient.writeData("/li","22222222",7);
        /*System.out.println(zkClient.writeDataReturnStat("/li","22222222",8).toString());
        System.out.println(zkClient.readData("/li",true));*/

        //删除node
        /*zkClient.delete("/li");
        //递归删除node
        zkClient.deleteRecursive("/test");*/

        //其他方法
        //有几个子节点
        int c = zkClient.countChildren("/");
        System.out.println("/ 有子节点:"+ c);
        //判断节点是否存在
        System.out.println(zkClient.exists("/aaa"));
        //子节点
        List<String> child = zkClient.getChildren("/");
        System.out.println("子节点:"+child);
        //获取节点创建的时间
        System.out.println(zkClient.getCreationTime("/aaa"));
        //将zkserver的目录结构输出到文件中
        zkClient.showFolders(new FileOutputStream("F:/test/123.txt"));

        zkClient.close();
    }
}
